import 'dart:math';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';

import 'ly_dash_line.dart';

typedef MetaHumanEditEndCallBack = void Function(double x, double y, double width, double height);
typedef MetaHumanDeleteClickCallBack = void Function();

class MetaHumanEditView extends StatefulWidget {
  final Widget contentWidget;
  final Size size;
  final double containerWidth;
  final double containerHeight;
  final bool borderVisible = true;
  final MetaHumanEditEndCallBack? endEditCallBack;
  final double aspectRatio;
  final Color? borderColor;
  final MetaHumanDeleteClickCallBack? deleteCallBack;
  const MetaHumanEditView(
      {super.key,
      required this.contentWidget,
      required this.containerWidth,
      required this.containerHeight,
      this.endEditCallBack,
      this.deleteCallBack,
      this.size = const Size(100, 100),
      this.aspectRatio = 9.0 / 16.0,
      this.borderColor});

  @override
  State<MetaHumanEditView> createState() => _MetaHumanEditViewState();
}

class _MetaHumanEditViewState extends State<MetaHumanEditView> {
  final double _space = 48;
  Offset _updateMoveOffset = Offset.zero;
  Offset _startMoveOffset = Offset.zero;
  Offset _endMoveOffset = Offset.zero;
  bool _isMoving = false;
  double _itemWidth = 0;
  double _itemHeight = 0;
  double _endWidth = 0;
  double _endHeight = 0;
  late final double _minWidth;
  late final double _minHeight;
  double _scale = 1.0;
  double _x = 0;
  double _y = 0;
  double _halfContainerWidth = 0;
  double _halfContainerHeight = 0;
  bool _borderVisible = true;

  Offset _panStartOffset = Offset.zero;
  Offset _panUpdateOffset = Offset.zero;
  Offset _panIntervalOffset = Offset.zero;
  late final double _itemScale;
  double _lastOffsetX = 0;
  double _lastOffsetY = 0;

  @override
  void initState() {
    super.initState();
    _itemWidth = widget.size.width;
    _itemHeight = widget.size.height;
    _minWidth = _itemWidth * 0.5;
    _minHeight = _itemHeight * 0.5;
    debugPrint('=======${widget.containerWidth}=${widget.containerHeight}');
    _halfContainerWidth = widget.containerWidth * 0.5;
    _halfContainerHeight = widget.containerHeight * 0.5;
    _x = _halfContainerWidth - _itemWidth * 0.5;
    _x = _halfContainerHeight - _itemHeight * 0.5;
    _borderVisible = widget.borderVisible;
    _itemScale = _itemHeight / _itemWidth;
  }

  void _updateItemSize() {
    final width = _endWidth * _scale;
    final height = _endHeight * _scale;
    _itemWidth = max(_minWidth, width);
    _itemHeight = max(_minHeight, height);
    setState(() {});
  }

  void _borderOnTap() {
    setState(() {
      _borderVisible = true;
    });
  }

  void _onScaleStart(ScaleStartDetails details) {
    _startMoveOffset = details.localFocalPoint;
    _isMoving = true;
  }

  void _onScaleEnd(ScaleEndDetails details) {
    _endMoveOffset = _updateMoveOffset;
    _isMoving = false;
    _endHeight = _itemHeight;
    _endWidth = _itemWidth;
    final deltaW = _itemWidth * 0.5 - _endMoveOffset.dx;
    final deltaH = _itemHeight * 0.5 - _endMoveOffset.dy;
    _x = _halfContainerWidth - deltaW;
    _y = _halfContainerHeight - deltaH;
    debugPrint("onScaleEnd=$_x=$_y");
    if (widget.endEditCallBack != null) {
      widget.endEditCallBack!(_x, _y, _itemWidth, _itemHeight);
    }
    setState(() {});
  }

  void _onScaleUpdate(ScaleUpdateDetails details) {
    if (details.pointerCount == 1) {
      Offset intervalOffset = details.localFocalPoint - _startMoveOffset + _endMoveOffset;
      // debugPrint("${details.toString()}\n");
      if (intervalOffset.dx < 20 && intervalOffset.dx > -20) {
        intervalOffset = Offset(0, intervalOffset.dy);
      }
      if (intervalOffset.dy < 20 && intervalOffset.dy > -20) {
        intervalOffset = Offset(intervalOffset.dx, 0);
      }
      setState(() {
        _updateMoveOffset = intervalOffset; // 更新坐标
      });
    } else if (details.pointerCount == 2) {
      _scale = details.scale;
      _updateItemSize();
    }
  }

  void _updateContentSize(double size) {
    final width = _endWidth - size;
    final height = _endHeight - size * _itemScale;
    _itemWidth = max(_minWidth, width);
    _itemHeight = max(_minHeight, height);
    setState(() {});
  }

  @override
  void didUpdateWidget(covariant MetaHumanEditView oldWidget) {
    super.didUpdateWidget(oldWidget);
    _halfContainerWidth = widget.containerWidth * 0.5;
    _halfContainerHeight = widget.containerHeight * 0.5;
    final deltaW = _itemWidth * 0.5 - _endMoveOffset.dx;
    final deltaH = _itemHeight * 0.5 - _endMoveOffset.dy;
    _x = _halfContainerWidth - deltaW;
    _y = _halfContainerHeight - deltaH;
    if (widget.endEditCallBack != null) {
      widget.endEditCallBack!(_x, _y, _itemWidth, _itemHeight);
    }
  }

  @override
  Widget build(BuildContext context) {
    return Stack(
      alignment: Alignment.center,
      children: [
        Positioned(
          width: _itemWidth + _space,
          height: _itemHeight + _space,
          child: Transform.translate(
              offset: _updateMoveOffset,
              child: GestureDetector(
                behavior: HitTestBehavior.translucent,
                onScaleStart: (details) => _onScaleStart(details),
                onScaleEnd: (details) => _onScaleEnd(details),
                onScaleUpdate: (details) => _onScaleUpdate(details),
                onTap: () => _borderOnTap(),
                child: SizedBox(
                  child: Stack(
                    children: [
                      Positioned(
                        child: Container(
                          margin: const EdgeInsets.all(24),
                          decoration: BoxDecoration(
                            border: _borderVisible
                                ? Border.all(color: widget.borderColor ?? Colors.black, width: 1)
                                : null,
                          ),
                          width: _itemWidth,
                          height: _itemHeight,
                        ),
                      ),
                      Positioned(
                        bottom: 12,
                        right: 12,
                        child: GestureDetector(
                          onPanStart: (details) {
                            // 激活图标
                            _panStartOffset = details.localPosition;
                          },
                          onPanUpdate: (details) {
                            _panUpdateOffset = details.localPosition;
                            _panIntervalOffset = -_panUpdateOffset + _panStartOffset;
                            _updateContentSize(_panIntervalOffset.dx);
                            debugPrint("=${details.toString()}");
                          },
                          onPanEnd: ((details) {
                            _endWidth = _itemWidth;
                            _endHeight = _itemHeight;
                          }),
                          child: Image.asset(
                            'assets/images/scale_size.jpg',
                            width: 24,
                            height: 24,
                          ),
                        ),
                      ),
                      Positioned(
                        top: 12,
                        left: 12,
                        child: GestureDetector(
                          onTap: () {
                            debugPrint("-----deleteCallBack-----");
                            if (widget.deleteCallBack != null) {
                              widget.deleteCallBack!();
                            }
                          },
                          child: Image.asset(
                            'assets/images/delete_icon.jpg',
                            width: 24,
                            height: 24,
                          ),
                        ),
                      ),
                    ],
                  ),
                ),
              )),
        ),
        Positioned(
          child: ClipRect(
            child: SizedBox(
              width: widget.containerWidth,
              height: widget.containerHeight,
              child: Stack(
                alignment: Alignment.center,
                children: [
                  Positioned(
                    width: _itemWidth,
                    height: _itemHeight,
                    child: Transform.translate(
                        offset: _updateMoveOffset,
                        child: IgnorePointer(
                          child: SizedBox(
                              width: _itemWidth, height: _itemHeight, child: widget.contentWidget),
                        )),
                  ),
                ],
              ),
            ),
          ),
        ),
        _makeDashLine(axis: Axis.horizontal, distance: _updateMoveOffset.dy),
        _makeDashLine(axis: Axis.vertical, distance: _updateMoveOffset.dx),
      ],
    );
  }

  Widget _makeDashLine({required Axis axis, required double distance}) {
    if (axis == Axis.horizontal) {
      if (distance == 0 && _lastOffsetX != 0) {
        HapticFeedback.mediumImpact(); //添加振动反馈
      }
      _lastOffsetX = distance;
    } else {
      if (distance == 0 && _lastOffsetY != 0) {
        HapticFeedback.mediumImpact(); //添加振动反馈
      }
      _lastOffsetY = distance;
    }
    return IgnorePointer(
      child: Visibility(
        visible: _isMoving,
        child: LYDashLine(
          axis: axis,
          lineColor: (Color.fromRGBO(
              0, 0, 0, (distance < 20 && distance > -20) ? (1 - distance.abs() / 20) : 0)),
        ),
      ),
    );
  }
}
